﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Management;
using System.Data;
using System.Diagnostics;
using System.Collections;
using System.IO;
using log4net;

namespace RollBackLib.src.sys
{
    /**
     * 
     */
    public class Sysutils
    {
        private static volatile Sysutils instance;
        private static object syncRoot = new Object();
        private static readonly ILog log = LogManager.GetLogger(typeof(Sysutils));

        public static Sysutils Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new Sysutils();
                    }
                }
                return instance;
            }
        }

        public ManagementObjectCollection getDrives()
        {
            //get drive collection
            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_LogicalDisk ");
            ManagementObjectCollection queryCollection = query.Get();

            return queryCollection;
        }

        public String[] getDriveNames(ManagementObjectCollection c)
        {
            var l = new String[c.Count];
            int i=0;
            foreach (var k in c)
            {
                String s = k["Name"].ToString();
                l[i++] = s;
                Trace.WriteLine(s);
            }
            return l;
        }

        /// <summary>
        /// Get drive with maximum free disk space
        /// </summary>
        /// <returns></returns>
        public string getDriveWithMaxFreeDiskspace()
        {
            System.IO.DriveInfo[] info = System.IO.DriveInfo.GetDrives();
            DriveInfo max = null; //TODO: Change this to get the system drive as the default, which can be sometheing other than C:\
            foreach(DriveInfo i in info) {
                try
                {
                    if (max == null || (i.AvailableFreeSpace > max.AvailableFreeSpace) )
                    {
                        max = i;
                    }
                }
                catch (IOException e)
                {
                    log.Info("Ignoring exception while enumerating disk for max free space", e);
                }
            }
            return max.Name;
        }

    }
}
